//
//  HYSelectInvitersVC.m
//  Booking
//
//  Created by Duntech on 2018/4/25.
//  Copyright © 2018年 Duntech. All rights reserved.
//

#import "HYSelectInvitersVC.h"
#import "HYMeetingInviterModel.h"
#import "HYSelectInviterCell.h"
#import "QQTagView.h"
#import "PinYin4Objc.h"

@interface HYSelectInvitersVC () <QQTagViewDelegate, UITableViewDelegate, UITableViewDataSource>{
    // 所有的indexsTitles
    NSArray *_allIndexTitles;
    // 存放索引对应的下标
    NSMutableArray *_sectionIndexs;
    // dataSource
    NSMutableArray *_data;
}
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) HYSelectInviterCell *previousSelectCell;
@property (nonatomic,strong) HYSelectInviterCellModel *previousCellModel;
@property (nonatomic,strong) QQTagView *tagView;
@property (nonatomic,strong) UIView *searchLine;
// allDataSource
@property (nonatomic,strong) NSMutableArray *allContacts;

@end


@implementation HYSelectInvitersVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self setupSubviews];
    [self requestNetwork];
}

- (void)setupSubviews{
    
    if (self.selectType == HYSelectTypeSingle) {
        self.title = NSLocalizedString(@"selectOrganizer", nil);
    }
    else{
        self.title = NSLocalizedString(@"selectInvitees", nil);
    }
    self.view.backgroundColor = KAPP_WHITE_COLOR;
    [self.view addSubview:self.searchLine];
    [self.view addSubview:self.tagView];
    [self.view addSubview:self.tableView];
    
    [_searchLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(10);
        make.right.equalTo(self.view).offset(-10);
        make.bottom.equalTo(self.tagView);
        make.height.mas_equalTo(1);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.searchLine.mas_bottom);
    }];
    
    UIBarButtonItem *okItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"ok", nil) style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnAction)];
    self.navigationItem.rightBarButtonItem = okItem;
}

- (void)requestNetwork{
    
    [HYNetRequestHandle getMeetingInviterListWithPageNo:@"" pageSize:@"" Complection:^(NSArray *meetingInviterList) {
        [meetingInviterList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            HYSelectInviterCellModel *cellModel = [HYSelectInviterCellModel modelWithDictionary:obj];
            cellModel.cellHeight = 60 * WIDTH_MULTIPLE;
            cellModel.cellIdientifier = @"HYSelectInviterCell";
            cellModel.isSelected = NO;
            [self.allContacts addObject:cellModel];
        }];
        [self sortObjectsAccordingToInitialWith:self.allContacts];
        [self.tableView reloadData];
    }];
}

#pragma mark - action
- (void)rightBtnAction{

    if (self.selectBlock) {

        NSMutableArray *userIDArray = [NSMutableArray array];
        NSMutableArray *usernameArray = [NSMutableArray array];
        
        for (NSArray *sectionArr in _data) {
            for (HYSelectInviterCellModel *cellModel in sectionArr) {
                
                if (cellModel.isSelected) {
                    
                    [userIDArray addObject:cellModel.id];
                    [usernameArray addObject:cellModel.realName];
                }
            }
        }
        
        if (userIDArray.count < 1) {
            [JRToast showWithText:NSLocalizedString(@"selectObject", nil) duration:2];
            return;
        }

        self.selectBlock(userIDArray, usernameArray);
        [self.navigationController popViewControllerAnimated:YES];
    }
}

// 按首字母分组排序数组
-(void)sortObjectsAccordingToInitialWith:(NSArray *)contacts {
    // 按照 ZJContact中的name来处理
    SEL nameSelector = @selector(realName);
    // 单例对象
    UILocalizedIndexedCollation *localIndex = [UILocalizedIndexedCollation currentCollation];
    // 获得当前语言下的所有的indexTitles
    _allIndexTitles = localIndex.sectionTitles;
    // 初始化所有数据的数组
    _data = [NSMutableArray arrayWithCapacity:_allIndexTitles.count];
    // 为每一个indexTitle 生成一个可变的数组
    for (int i = 0; i<_allIndexTitles.count; i++) {
        // 初始化数组
        [_data addObject:[NSMutableArray array]];
    }
    // 初始化有效的sectionIndexs
    _sectionIndexs = [NSMutableArray arrayWithCapacity:_allIndexTitles.count];
    for (HYSelectInviterCellModel *contact in contacts) {
        if (contact == nil) continue;
        
        // 获取到这个contact的name的首字母对应的indexTitle
        // 注意这里必须使用对象, 这个selector也是有要求的
        // 必须是这个对象中的selector, 并且不能有参数, 必须返回字符串
        // 所以这里直接使用 name 属性的get方法就可以
        NSInteger index = [localIndex sectionForObject:contact collationStringSelector:nameSelector];
        
        // 处理多音字 例如 "曾" -->> 会被当做 ceng 来处理, 其他需要处理的多音字类似
        if ([contact.realName hasPrefix:@"曾"]) {
            index = [_allIndexTitles indexOfObject:@"Z"];
        }
        // 将这个contact添加到对应indexTitle的数组中去
        [_data[index] addObject:contact];
    }
    
    for (int i=0; i<_data.count; i++) {
        NSArray *temp = _data[i];
        if (temp.count != 0) { // 取出不为空的部分对应的indexTitle
            [_sectionIndexs addObject:[NSNumber numberWithInt:i]];
        }
        // 排序每一个数组
        _data[i] = [localIndex sortedArrayFromArray:temp collationStringSelector:nameSelector];
    }
}

// 搜索联系人的方法 (拼音/拼音首字母缩写/汉字)
- (NSArray<HYSelectInviterCellModel *> *)searchText:(NSString *)searchText inDataArray:(NSArray<HYSelectInviterCellModel *> *)dataArray {
    NSMutableArray *results = [NSMutableArray array];
    // 参数不合法
    if (searchText.length <= 0 || dataArray.count <= 0) return results;
    
    if (isIncludeChineseInNSString(searchText)) { // 输入了中文-只查询中文
        for (HYSelectInviterCellModel *contact in dataArray) {
            NSRange resultRange = [contact.realName rangeOfString:searchText options:NSCaseInsensitiveSearch];
            if (resultRange.length > 0) {// 找到了
                [results addObject:contact];
            }
        }
        
    }
    else {
        for (HYSelectInviterCellModel *contact in dataArray) {
            
            if (isIncludeChineseInNSString(contact.realName)) {// 待查询中有中文--转为拼音
                // 设置输入格式
                HanyuPinyinOutputFormat *outputFormat = [[HanyuPinyinOutputFormat alloc] init];
                [outputFormat setToneType:ToneTypeWithoutTone];
                [outputFormat setVCharType:VCharTypeWithV];
                [outputFormat setCaseType:CaseTypeLowercase];
                
                static NSString *const separatorString = @" ";
                // 获取到每个汉字拼音之间有分隔符的拼音
                NSString *completeHasSeparatorPinyin = [PinyinHelper toHanyuPinyinStringWithNSString:contact.realName withHanyuPinyinOutputFormat:outputFormat withNSString:separatorString];
                // 处理多音字 -- 这里只处理了 '曾'
                if ([contact.realName hasPrefix:@"曾"] && [completeHasSeparatorPinyin hasPrefix:@"c"]) {
                    completeHasSeparatorPinyin = [completeHasSeparatorPinyin stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"z"];
                }
                // 删除分隔符
                NSString *completeNOSeparatorPinyin = [completeHasSeparatorPinyin stringByReplacingOccurrencesOfString:separatorString withString:@""];
                
                // 查询没有分隔符中是否包含 (不能使用有分隔符的拼音来查询, 因为输入的里面可能不会包含分隔符, 导致查询不到)
                NSRange resultRange = [completeNOSeparatorPinyin rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (resultRange.length > 0) {// 找到了
                    [results addObject:contact];
                    continue; // 进入下一次循环, 不再执行下面这段代码
                }
                NSMutableString *headOfPinyin = [NSMutableString string];
                NSArray *pinyinArray = [completeHasSeparatorPinyin componentsSeparatedByString:separatorString];
                for (NSString *singlePinyin in pinyinArray) {
                    if (singlePinyin) { // 取每个拼音的首字母
                        [headOfPinyin appendString:[singlePinyin substringToIndex:1]];
                    }
                }
                
                NSRange headResultRange = [headOfPinyin rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (headResultRange.length > 0) {// 找到了
                    [results addObject:contact];
                }
                
            }
            else { // 姓名是英文的, 那么直接查询英文
                NSRange resultRange = [contact.realName rangeOfString:searchText options:NSCaseInsensitiveSearch];
                if (resultRange.length > 0) {// 找到了
                    [results addObject:contact];
                }
            }
            
        }
        
    }
    return results;
}

static BOOL isIncludeChineseInNSString(NSString *string) {
    for (int i=0; i<string.length; i++) {
        unichar ch = [string characterAtIndex:i];
        if (0x4e00 < ch  && ch < 0x9fff) {
            return true;
        }
    }
    return false;
}

#pragma mark - UITableViewDataSource


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _sectionIndexs.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger index = [_sectionIndexs[section] integerValue];
    NSArray *temp = _data[index];
    return temp.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *const kCellId = @"HYSelectInviterCell";
    HYSelectInviterCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    
    NSInteger index = [_sectionIndexs[indexPath.section] integerValue];
    NSArray *temp = _data[index];
    HYSelectInviterCellModel *contact = (HYSelectInviterCellModel *)temp[indexPath.row];
    [cell configWithModel:contact];
    return cell;
}

#pragma mark - UITableViewDelegate

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSInteger index = [_sectionIndexs[section] integerValue];
    return _allIndexTitles[index];
}

// 这个方法是返回索引的数组, 我们需要根据之前获取到的两个数组来取到我们需要的
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    NSMutableArray *indexTitles = [NSMutableArray arrayWithCapacity:_sectionIndexs.count];
    // 遍历索引的下标数组, 然后根据下标取出_allIndexTitles对应的索引字符串
    for (NSNumber *number in _sectionIndexs) {
        NSInteger index = number.integerValue;
        [indexTitles addObject:_allIndexTitles[index]];
    }
    return indexTitles;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    HYSelectInviterCell *cell = (HYSelectInviterCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    NSInteger index = [_sectionIndexs[indexPath.section] integerValue];
    NSArray *temp = _data[index];
    HYSelectInviterCellModel *cellModel = (HYSelectInviterCellModel *)temp[indexPath.row];

    if (self.selectType == HYSelectTypeSingle) {

        self.previousCellModel.isSelected = NO;
        self.previousSelectCell.selectBtn.selected = NO;
        cellModel.isSelected = !cellModel.isSelected;
        cell.selectBtn.selected = cellModel.isSelected;
        [self.tagView removeAllLabel];
        [self.tagView addLabel:cellModel.realName tag:101];
    }
    else{

        cellModel.isSelected = !cellModel.isSelected;
        cell.selectBtn.selected = cellModel.isSelected;
        if ([self.tagView isExistWithLabel:cellModel.realName]) {
            [self.tagView remove:cellModel.realName];
        }
        else{
            [self.tagView addLabel:cellModel.realName tag:101];
        }
    }
    self.previousSelectCell = cell;
    self.previousCellModel = cellModel;
    
    [self.view endEditing:YES];
}

// 可以相应点击的某个索引, 也可以为索引指定其对应的特定的section, 默认是 section == index
// 返回点击索引列表上的索引时tableView应该滚动到那一个section去
// 这里我们的tableView的section和索引的个数相同, 所以直接返回索引的index即可
// 如果不相同, 则需要自己相应的返回自己需要的section
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
    return index;
}

#pragma mark - QQTagViewDelegate
- (void)QQTagView:(QQTagView *)QQTagView QQTagItem:(QQTagItem *)QQTagItem{
    NSLog(@"=====%@",QQTagItem.text);
    [self.tagView remove:QQTagItem.text];
    
    for (NSArray *sectionArr in _data) {
        for (HYSelectInviterCellModel *cellModel in sectionArr) {
            
            if ([cellModel.realName isEqualToString:QQTagItem.text]) {
                cellModel.isSelected = NO;
            }
        }
    }
    [self.tableView reloadData];
}

-(void)QQTagView:(QQTagView *)QQTagView searchText:(NSString *)text{
    NSArray *contacts =  [self searchText:text inDataArray:self.allContacts];
    if (text.length) {
        contacts =  [self searchText:text inDataArray:self.allContacts];
    }
    else{
        contacts =  self.allContacts;
    }
    [self sortObjectsAccordingToInitialWith:contacts];
    [self.tableView reloadData];
}

#pragma mark - lazyload

- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.backgroundColor = KAPP_WHITE_COLOR;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[HYSelectInviterCell class] forCellReuseIdentifier:@"HYSelectInviterCell"];
    }
    return _tableView;
}

- (QQTagView *)tagView{
    
    if (!_tagView) {
        _tagView = [[QQTagView alloc]initWith:QQTagStyleEditSlect];
        _tagView.frame = CGRectMake(0, 0, kScreenWidth, 45);
        _tagView.backgroundColor = KAPP_WHITE_COLOR;
        _tagView.tag = 101;
        _tagView.delegate = self;
    }
    return _tagView;
}

- (UIView *)searchLine{
    
    if (!_searchLine) {
        
        _searchLine = [UIView new];
        _searchLine.backgroundColor = KAPP_SEPERATOR_COLOR;
    }
    return _searchLine;
}

-(NSMutableArray *)allContacts{
    if (!_allContacts) {
        _allContacts = [NSMutableArray new];
    }
    return _allContacts;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
